﻿
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace Utity
{
    public class AppHelper
    {
        public string ConvertToMD5(string sign)
        {
            byte[] result = Encoding.UTF8.GetBytes(sign);  
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "").ToLower();  //tbMd5pass为输出加密文本的文本框
        }

        public  string PostDictToString(object paramValues)
        {
            List<string> lst = new List<string>();
            if (paramValues is Dictionary<string, string>)
            {
                Dictionary<string, string> dic = (Dictionary<string, string>)paramValues;
                foreach (string k in dic.Keys)
                {
                    lst.Add(string.Format("{0}={1}", k, dic[k]));
                }
            }
            else if (paramValues is Dictionary<string, object>)
            {
                Dictionary<string, object> dic = (Dictionary<string, object>)paramValues;
                foreach (string k in dic.Keys)
                {
                    lst.Add(string.Format("{0}={1}", k, dic[k].ToString()));
                }
            }
            else
            {
                throw new Exception("参数格式异常");
            }
            string s = string.Join("&", lst.ToArray());
            return s;
        }

        public string Send(string url, string postData, Encoding code,string addHeaderToken)
        {
            byte[] byteArray = code.GetBytes(postData);
            const string key = "BBFFTT!@#QWE";
            // Debug.Print("发送前时间:" + DateTime.Now.ToString("HH:mm:ss fff"));
            ServicePointManager.ServerCertificateValidationCallback += CheckValidationResult;
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));

            webRequest.Method = "POST";
            webRequest.KeepAlive = true;
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Timeout = 5 * 1000;
            webRequest.ContentLength = byteArray.Length;
            if (!string.IsNullOrEmpty(addHeaderToken))
            {
                webRequest.Headers.Add("INSURE_REQUIRE_CLASS", addHeaderToken);
                webRequest.Headers.Add("REQ_KEY", ConvertToMD5(key + addHeaderToken));
            }

            Stream newStream = webRequest.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();

            string returnJson = "";
            using (Stream stream = webRequest.GetResponse().GetResponseStream())
            {
                using (StreamReader sread = new StreamReader(stream))
                {
                    returnJson = sread.ReadToEnd();
                    returnJson = DecodeBase64(code, returnJson);
                }
                webRequest.GetResponse().Close();
            }

            if (webRequest != null)
            {
                webRequest.Abort();
            }
           
            // Debug.Print("发送后时间:" + DateTime.Now.ToString("HH:mm:ss fff"));
            // Debug.WriteLine(returnJson);
            return returnJson;
        }

        public string BaseSend(string url, Stream stm)
        {
            byte[] byteArray = new byte[stm.Length];
            stm.Read(byteArray, 0, byteArray.Length);
            // 设置当前流的位置为流的开始
            stm.Seek(0, SeekOrigin.Begin);
            stm.Close();

            ServicePointManager.ServerCertificateValidationCallback += CheckValidationResult;
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));

            webRequest.Method = "POST";
            webRequest.KeepAlive = true;
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Timeout = 5 * 1000;
            webRequest.ContentLength = byteArray.Length;

            Stream newStream = webRequest.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();

            string returnJson = "";
            using (Stream stream = webRequest.GetResponse().GetResponseStream())
            {
                using (StreamReader sread = new StreamReader(stream))
                {
                    returnJson = sread.ReadToEnd();
                }
                webRequest.GetResponse().Close();
            }

            if (webRequest != null)
            {
                webRequest.Abort();
            }

            // Debug.Print("发送后时间:" + DateTime.Now.ToString("HH:mm:ss fff"));
            // Debug.WriteLine(returnJson);
            return returnJson;
        }


        public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   // 总是接受
            return true;
        }

        public string EncodeBase64(Encoding encode, string source)
        {
            string str = "";
            byte[] bytes = encode.GetBytes(source);
            try
            {
                str = Convert.ToBase64String(bytes);
            }
            catch
            {
                str = source;
            }
            return str;
        }

        public string DecodeBase64(Encoding encode, string result)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decode = encode.GetString(bytes);
            }
            catch
            {
                decode = result;
            }
            return decode;
        }



        public string ConvertToGBK(string data)
        {
            Byte[] encodedBytes = Encoding.GetEncoding("GBK").GetBytes(data);
            return Encoding.GetEncoding("GBK").GetString(encodedBytes);
        }

    }
}
